<template>
  <view class="normal-login-container">
    <view class="logo-content align-center justify-center flex">
      <image
        style="width: 100rpx; height: 100rpx"
        :src="globalConfig.appInfo.logo"
        mode="widthFix"
      >
      </image>
      <text class="title">美控后台移动端登录</text>
    </view>
    <view class="login-form-content">
      <view class="input-item flex align-center">
        <view class="iconfont icon-user icon"></view>
        <input
          v-model="loginForm.username"
          class="input"
          type="text"
          placeholder="请输入账号"
          maxlength="30"
        />
      </view>
      <view class="input-item flex align-center">
        <view class="iconfont icon-password icon"></view>
        <input
          v-model="loginForm.password"
          type="password"
          class="input"
          placeholder="请输入密码"
          maxlength="20"
        />
      </view>
      <view
        class="input-item flex align-center"
        style="width: 60%; margin: 0px"
        v-if="!captchaEnabled"
      >
        <view class="iconfont icon-code icon"></view>
        <input
          v-model="loginForm.code"
          type="number"
          class="input"
          placeholder="请输入验证码"
          maxlength="4"
        />
        <view class="login-code">
          <image
            :src="codeUrl"
            @tap="getCode"
            class="login-code-img"
          ></image>
        </view>
      </view>
      <view class="action-btn">
        <button
          @tap="handleLogin"
          class="login-btn cu-btn block bg-blue lg round"
        >
          登录
        </button>
        <button
          @tap="wxHandleLogin"
          class="login-btn cu-btn block lg bg-green round"
        >
          微信授权登录
        </button>
      </view>
    </view>

    <view class="xieyi text-center">
      <checkbox-group>
        <view
          class="clickGrey"
          @click="onchange"
          style="display: inline-block"
        >
          <checkbox :checked="checked" />
          <text
            class="text-grey1"
            style="margin-left: 20rpx"
            >同意</text
          >
        </view>
        <!-- <text @tap="handleUserAgrement" class="text-blue">《用户协议》</text> -->
        <text
          @tap="handlePrivacy"
          class="text-blue"
          >《用户隐私保护指引》</text
        >
      </checkbox-group>
    </view>
  </view>
</template>

<script>
  import { getCodeImg } from '@/api/login'
  import { getToken } from '@/utils/auth'
  import {
    getEquipment,
    updateEquipment,
  } from '@/api/system/equiment/equipment.js'
  import { listMessage } from '@/api/system/message/message.js'
  export default {
    data() {
      return {
        checked: false,
        codeUrl: '',
        equipmentNo: '',
        captchaEnabled: true,
        globalConfig: getApp().globalData.config,
        openid: '',
        session_key: '',
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: null,
          templateId: null,
        },
        loginForm: {
          username: '',
          password: '',
          code: '',
          uuid: '',
        },
        //微信登录
        wxLoginForm: {
          code: '',
          encryptedIv: '',
          encryptedData: '',
        },
        tmplIds: [],
        ids: null,
        flag: false, //防止多次点击
      }
    },
    created() {
      //this.getCode()
    },
    //获取进入本界面的设备id
    onLoad(option) {
      if (getToken()) {
        //检查登录是否过期
        uni.checkSession({
          success: (res) => {
            if (res.errMsg == 'checkSession:ok') {
              uni.reLaunch({
                url: '/pages/index',
              })
            }
          },
          fail: (err) => {
            //过期的话调用接口
            uni.showModal({
              cancelText: '取消',
              confirmText: '确定',
              title: '登录已过期,请重新登录',
            })
          },
        })
      }
    },
    methods: {
      onchange() {
        if (this.checked) {
          this.checked = false
        } else {
          this.checked = true
        }
      },
      // 隐私协议
      handlePrivacy() {
        // 打开隐私协议页面
        uni.openPrivacyContract({
          success: () => {}, // 打开成功
          fail: () => {}, // 打开失败
          complete: () => {},
        })
      },
      // 用户协议
      handleUserAgrement() {
        let site = this.globalConfig.appInfo.agreements[1]
        this.$tab.navigateTo(
          `/pages/common/webview/index?title=${site.title}&url=${site.url}`
        )
      },
      // 获取图形验证码
      getCode() {
        getCodeImg().then((res) => {
          this.captchaEnabled =
            res.captchaEnabled === undefined ? true : res.captchaEnabled
          if (this.captchaEnabled) {
            this.codeUrl = 'data:image/gif;base64,' + res.img
            this.loginForm.uuid = res.uuid
          }
        })
      },
      //微信授权登录
      async wxHandleLogin() {
        if (this.checked == false) {
          this.$modal.msg('请先勾选同意用户隐私保护指引')
        } else {
          if (!this.flag) {
            this.flag = true
            //向后发起登录请求
            this.$modal.loading('登录中，请耐心等待...')
            this.sendSubscriptions(2)
          }
        }
      },

      //微信授权登录方法
      wxLoginHanld() {
        //获取服务商信息
        uni.getProvider({
          service: 'oauth',
          success: (res) => {
            if (~res.provider.indexOf('weixin')) {
              //登录
              uni.login({
                provider: 'weixin',
                success: (loginRes) => {
                  this.wxLoginForm.code = loginRes.code
                  uni.getUserInfo({
                    success: (resInfo) => {
                      //设置偏移量和加密数据
                      this.wxLoginForm.encryptedData = resInfo.encryptedData
                      this.wxLoginForm.encryptedIv = resInfo.iv
                      this.sendWxLoginFormToLocalService()
                    },
                  })
                },
              })
            }
          },
        })
      },
      //向后端发起登录请求
      sendWxLoginFormToLocalService() {
        this.$store
          .dispatch('wxLogin', this.wxLoginForm)
          .then(() => {
            this.$modal.closeLoading()
            this.loginSuccess(2)
          })
          .catch(() => {
            this.$modal.closeLoading()
            this.$modal.msgError('微信登录失败！')
          })
      },
      // 登录方法
      /*
      else if (this.loginForm.code === "" && this.captchaEnabled) {
        this.$modal.msgError("请输入验证码")
      }*/
      //账号登录
      async handleLogin() {
        if (this.loginForm.username === '') {
          this.$modal.msgError('请输入您的账号')
        } else if (this.loginForm.password === '') {
          this.$modal.msgError('请输入您的密码')
        } else if (this.checked == false) {
          this.$modal.msg('请先勾选同意用户隐私保护指引')
        } else {
          this.$modal.loading('登录中，请耐心等待...')
          this.sendSubscriptions(1)
        }
      },
      // 密码登录
      async pwdLogin() {
        this.$store
          .dispatch('Login', this.loginForm)
          .then(() => {
            this.$modal.closeLoading()
            this.loginSuccess(1)
          })
          .catch(() => {
            if (this.captchaEnabled) {
              this.$modal.closeLoading()
              this.getCode()
            }
          })
      },
      // 登录成功后，处理函数
      loginSuccess(result) {
        // 设置用户信息
        this.$store.dispatch('GetInfo').then((res) => {
          if (result == 2 && this.$store.state.user.name == '微信用户') {
            this.$tab.reLaunch('/pages/mine/info/edit')
            uni.setStorageSync('userId', this.$store.state.user.userId)
          } else {
            this.$tab.reLaunch('/pages/index')
            uni.setStorageSync('userId', this.$store.state.user.userId)
          }
        })
      },
      //发送消息方法
      sendSubscriptions(state) {
        const thant = this
        uni.getSetting({
          withSubscriptions: true,
          success: (res) => {
            //判断是否点击订阅
            if (res.subscriptionsSetting.mainSwitch) {
              //查询用户订阅的消息有哪些
              listMessage(thant.queryParams).then((response) => {
                if (response.code == 200 && response.rows[0] != null) {
                  thant.ids = response.rows.map((item) => item.id)
                  thant.tmplIds = response.rows.map((item) => item.templateId)
                  uni.requestSubscribeMessage({
                    tmplIds: thant.tmplIds,
                    success: (res) => {
                      thant.flag = false
                      if (state == 1) {
                        thant.pwdLogin()
                      } else {
                        thant.wxLoginHanld()
                      }
                    },
                    fail(err) {
                      thant.flag = false
                    },
                  })
                } else {
                  thant.flag = false
                  thant.$tab.reLaunch('/pages/index')
                }
              })
            } else {
              thant.flag = false
              uni.showModal({
                title: '提示',
                content: '您已关闭消息订阅，请开启后再进行操作',
                showCancel: false,
              })
            }
          },
        })
      },
    },
  }
</script>

<style lang="scss">
  page {
    background-color: #ffffff;
  }

  .normal-login-container {
    width: 100%;

    .logo-content {
      width: 100%;
      font-size: 21px;
      text-align: center;
      padding-top: 15%;

      image {
        border-radius: 4px;
      }

      .title {
        margin-left: 10px;
      }
    }

    .login-form-content {
      text-align: center;
      margin: 20px auto;
      margin-top: 15%;
      width: 80%;

      .input-item {
        margin: 20px auto;
        background-color: #f5f6f7;
        height: 45px;
        border-radius: 20px;

        .icon {
          font-size: 38rpx;
          margin-left: 10px;
          color: #999;
        }

        .input {
          width: 100%;
          font-size: 14px;
          line-height: 20px;
          text-align: left;
          padding-left: 15px;
        }
      }

      .login-btn {
        margin-top: 40px;
        height: 45px;
      }

      .xieyi {
        color: #333;
        margin-top: 20px;
      }

      .login-code {
        height: 38px;
        float: right;

        .login-code-img {
          height: 38px;
          position: absolute;
          margin-left: 10px;
          width: 200rpx;
        }
      }
    }
  }
</style>
